//
//  YSPageView.m
//  YSPageViewExample_OC
//
//  Created by MOLBASE on 2017/12/5.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSPageView.h"
#import "YSTitleView.h"
#import "YSContentView.h"
#import "UIView+YSFrame.h"
#import "UIColor+YSExtension.h"

@interface YSPageView ()

@property (nonatomic, strong) NSArray<NSString *> *titleArray;
@property (nonatomic, strong) NSArray<UIViewController *> *childVcArray;
@property (nonatomic, weak  ) UIViewController *parentVc;
@property (nonatomic, strong) YSPageStyle *style;

@property (nonatomic, strong) YSTitleView *titleView;
@property (nonatomic, strong) YSContentView *contentView;

@end

@implementation YSPageView

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray<NSString *> *)titleArray childVcs:(NSArray<UIViewController *> *)childVcArray parentVc:(UIViewController *)parentVc style:(YSPageStyle *)style {
    if ([self initWithFrame:frame]) {
        self.titleArray = titleArray;
        self.childVcArray = childVcArray;
        self.parentVc = parentVc;
        self.style = style;
        self.parentVc.automaticallyAdjustsScrollViewInsets = NO;
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    if (!self.titleArray || !self.childVcArray || self.titleArray.count == 0 || self.childVcArray.count == 0 || self.titleArray.count != self.childVcArray.count) {
        NSException *excp = [NSException exceptionWithName:@"YSPageViewException" reason:@"传入的标题数组和控制器数组不匹配，请检查。" userInfo:nil];
        [excp raise];
    }
    
    if (self.style.selectIndex > self.titleArray.count-1) {
        self.style.selectIndex = self.titleArray.count - 1;
    } else if (self.style.selectIndex < 0) {
        self.style.selectIndex = 0;
    }
    
    // 1. 添加ContentView
    [self setupContentView];
    
    // 2. 添加TitleView
    [self setupTitleView];
    
    // 3. 互为代理
    self.titleView.delegate = (id)self.contentView;
    self.contentView.delegate = (id)self.titleView;
    
}

- (void)setupTitleView {
    _titleView = [[YSTitleView alloc] initWithFrame:CGRectMake(0, 0, self.ys_width, self.style.titleHeight) titles:self.titleArray style:self.style];
    [self addSubview:_titleView];
}

- (void)setupContentView {
    CGFloat y = self.style.isFullScreen ? 0 : self.style.titleHeight;
    CGRect contentFrame = CGRectMake(0, y, self.ys_width, self.ys_height - y);
    _contentView = [[YSContentView alloc] initWithFrame:contentFrame childVcs:self.childVcArray parentVc:self.parentVc style:self.style];
    [self addSubview:_contentView];
}

@end
